package cn.monkey.chat.server.admin.domain.account;

import cn.monkey.chat.server.data.Result;
import cn.monkey.chat.server.data.Results;
import cn.monkey.chat.server.data.account.Account;
import cn.monkey.chat.server.data.account.AccountCreateReq;
import cn.monkey.chat.server.data.account.Authorization;
import cn.monkey.chat.server.data.account.SignInReq;
import reactor.core.publisher.Mono;

import java.util.UUID;

public class AccountService implements IAccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    @Override
    public Mono<Result<Authorization>> signIn(SignInReq req) {
        return accountRepository.findByUsername(req.getUsername())
                .filter(account -> account.getPassword().equals(req.getPassword()))
                .map(account -> {
                    Authorization authorization = new Authorization();
                    authorization.setUsername(account.getUsername());
                    authorization.setToken(UUID.randomUUID().toString());
                    return authorization;
                })
                .map(Results::ok)
                .switchIfEmpty(Mono.just(Results.fail("USER_NOT_FOUNT")));
    }

    @Override
    public Mono<Result<Account>> create(AccountCreateReq req) {
        return Mono.just(req)
                .map(r -> {
                    Account account = new Account();
                    account.setUsername(r.getUsername());
                    account.setPassword(r.getPassword());
                    return account;
                })
                .flatMap(this.accountRepository::save)
                .map(Results::ok);
    }
}
